<script setup lang="ts">
import AdditionalInformation from '@/subcontract/home/component/additionalInformation/index.vue';
import { useAppStore } from '@/store';
import useToast from '@/hooks/useToast';
import OrderRequest from '@/request/orderRequest';
import to from '@/utils/to';
import Tools from '@/utils/tools';
import { navigate } from '@/utils/navigate';
import { requestPayment } from '@/utils/requestPayment';

interface IState {
  data?: IGetBtnDefaultGoodsRes;
  nums: number;
  additionalFormAction: number;
  goodsAdditionalForm: IGoodsAdditionalInfo[][];
  additionalForm: IGoodsAdditionalInfo[][];
  resultAttrData: IGoodsAdditionalInfo[][];
}

const state = reactive<IState>({ nums: 1, goodsAdditionalForm: [], additionalForm: [], resultAttrData: [], additionalFormAction: 0 });
const store = useAppStore();
const { systemInfo } = store.$state;
const { showToast } = useToast();

onLoad((options) => {
  state.data = JSON.parse(decodeURIComponent(options!.data));
  const { attr } = state.data!;
  if (attr) {
    if (attr['1']) {
      Object.keys(attr['1']).forEach((key) => {
        state.goodsAdditionalForm.push(attr['1'][key]);
      });
      state.resultAttrData[0] = state.goodsAdditionalForm.flat(1);
    }
    if (attr['2']) {
      state.additionalForm = attr['2'];
      state.resultAttrData[1] = attr['2'][0];
    }
  }
});

// 附加信息组件change
const handleAdditionalInfoChange = (data: IGoodsAdditionalInfo, index: number) => {
  state.resultAttrData[index] = state.resultAttrData[index].map((item) => (item.attrId === data.attrId ? data : item));
};

// 提交订单
const handleSubmit = async () => {
  const { btnInformation, beeperId, userInfo } = useAppStore().$state;
  const { goodsId, goodsType, variantId } = state.data!.goods;
  const { harvestAddressId } = state.data!.addressInfo;
  const result = state.resultAttrData.flat();
  const required = result.find((item) => item.requiredFlag && !item.value);
  if (required) {
    await showToast(`${required.attrName}不能为空`);
    return;
  }
  const params = {
    goodsId,
    goodsType,
    variantId,
    beeperId,
    harvestAddressId,
    btnId: btnInformation!.id,
    nums: state.nums,
    openId: userInfo.openId,
    orderAttrs: await Promise.all(
      result.map(async (item) => {
        if (item.fieldType === 8 && item.value) {
          return { ...item, value: await Tools.uniBase64FromFile(item.value) };
        }
        return item;
      }),
    ),
  };
  const [err, res] = await to(OrderRequest.PullWeChatPayment({ ...params, hasLoading: true }));
  if (err) return;
  if (btnInformation!.eventId === 12) {
    const [payErr] = await to(requestPayment({ ...res.data, provider: 'wxpay', orderInfo: '' }));
    if (payErr) return;
  }
  navigate({ type: 'switchTab', url: '/pages/order/index' });
};
</script>

<template>
  <view class="c-pd h-screen overflow-scroll" :style="{ paddingBottom: `${44 + systemInfo.safeAreaInsets!.bottom}px` }" v-if="state.data">
    <view class="c-br c-pd bg-white flex mb-12px">
      <view class="w-80px h-80px c-br overflow-hidden">
        <image class="w-full h-full" :src="state.data.goods.mainImg" lazy-load mode="aspectFill" />
      </view>
      <view class="pl-8px box-border overflow-hidden flex-1 flex flex-col justify-between">
        <view class="flex items-start">
          <view class="flex-1 c-text-ellipsis-2 w-full fw-bold c-text-14">
            {{ state.data.goods.name }}
          </view>
          <view v-if="state.data.goods.visitFlag !== 0" class="ml-4px text-8px px-4px py-2px rounded-4px border-1px border-#999999 border-solid c-text-color-grey">服务上门</view>
        </view>
        <view class="c-text-ellipsis c-text-color-grey c-text-10" v-if="state.data.goods.introduce">{{ state.data.goods.introduce }}</view>
        <view class="c-text-ellipsis c-text-color-grey c-text-10" v-if="state.data.goods.remark">{{ state.data.goods.remark }}</view>
        <view class="flex justify-between">
          <view class="flex items-center h-full" v-if="state.data.goods.activePrice || state.data.goods.salePrice">
            <text class="text-red fw-bold c-text-12 mr-2px mt-3px">¥</text>
            <text class="text-red fw-bold c-text-16">{{ state.data.goods.activePrice !== null ? state.data.goods.activePrice : state.data.goods.salePrice }}</text>
            <text class="c-text-color-grey c-text-12 ml-6px line-through mt-1px" v-if="state.data.goods.activePrice === null && state.data.goods.salePrice !== state.data.goods.price">¥{{ state.data.goods.price }}</text>
            <text class="c-text-color-grey c-text-12 ml-6px line-through mt-1px" v-if="state.data.goods.activePrice !== null && state.data.goods.activePrice !== state.data.goods.price">¥{{ state.data.goods.price }}</text>
          </view>
          <view v-else />
          <view class="flex items-center" v-if="Tools.renderProductValidation(state.data.goods) !== 1">
            <i
              class="i-gg:remove c-color c-text-16"
              @click.stop="
                () => {
                  if (state.nums > 1) state.nums--;
                }
              "
            />
            <text class="mx-8px fw-bold c-text-14">{{ state.nums }}</text>
            <i class="i-icon-park-solid:add-one c-color c-text-16" @click.stop="state.nums++" />
          </view>
          <view v-else class="c-text-color-grey">非可售时间</view>
        </view>
      </view>
    </view>

    <view class="py-12px mb-12px c-pd bg-white c-br" v-for="(item, index) in state.goodsAdditionalForm" :key="index">
      <view class="fw-bold">{{ state.data.goods.name }} - 附加信息</view>
      <view class="c-text-12 c-text-color-grey" v-if="state.data.goods.introduce">{{ state.data.goods.introduce }}</view>
      <van-divider />
      <AdditionalInformation :formList="item" @change="({ data }) => handleAdditionalInfoChange(data, 0)" />
    </view>

    <template v-if="state.additionalForm.length !== 0">
      <view class="c-br mb-12px c-pd bg-white">
        <view class="fw-bold">附加信息</view>
        <van-divider />
        <van-tabs
          v-if="state.additionalForm.length > 1"
          :active="state.additionalFormAction"
          @change="
            (e: any) => {
              state.additionalFormAction = e.detail.name;
              state.resultAttrData[1] = state.additionalForm[e.detail.name];
            }
          "
        >
          <van-tab :title="`填写方式${index + 1}`" :name="index" v-for="(_, index) in state.additionalForm" :key="index" />
        </van-tabs>
        <AdditionalInformation :formList="state.additionalForm[state.additionalFormAction]" @change="({ data }) => handleAdditionalInfoChange(data, 1)" />
      </view>
    </template>
    <view class="pos-fixed left-0 px-12px w-screen box-border z-99" :style="{ bottom: `${systemInfo.safeAreaInsets!.bottom}px` }">
      <view v-if="Tools.renderProductValidation(state.data.goods) !== 1" class="c-bg text-white py-12px c-br text-align-center" @click="handleSubmit">提交订单</view>
      <view v-else class="bg-#9C9C9E text-white py-12px c-br text-align-center">非可售时间</view>
    </view>
  </view>
  <RecordingModal />
</template>

<style lang="scss" scoped>
@import './index.scss';
</style>
